﻿/*!
 *  Released under the MIT license
 *  template.js
 */

(function( global, factory ) {

    if ( typeof module === "object" && typeof module.exports === "object" ) {

        module.exports = global.document ?
            factory( global, true ) :
            function( w ) {
                if ( !w.document ) {
                    throw new Error( "T requires a window with a document" );
                }
                return factory( w );
            };
    } else {
        factory( global );
    }

// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {

    // 去除转义
    function esca(v){
        return v ?
            v.replace(/&lt;/g,"<").replace(/&quot;/g,"'").replace(/&gt;/g,">")
            : v;
    }

    function template(str, data) {
        return str.replace(/\{ *([\w_\$]+) *\}/g, function (str, key) {
            //去除转义
            var value = esca(data[key]);
            //console.log(value);
            if (value === undefined) {
                console.log('No value provided for variable ' + str);
                value = "{" + key + "}";
            } else if (typeof value === 'function') {
                value = value(data);
            }
            return value;
        })
    }

    // 路由
    function Router(){}

    Router.prototype = {
        routes : [],

        step : 0,
        // use backbone route mehtod
        _routeToRegExp: function(route) {
            var optionalParam = /\((.*?)\)/g;
            var namedParam    = /(\(\?)?:\w+/g;
            var splatParam    = /\*\w+/g;
            var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;
            route = route.replace(escapeRegExp, '\\$&')
                .replace(optionalParam, '(?:$1)?')
                .replace(namedParam, function(match, optional) {
                    return optional ? match : '([^/?]+)';
                })
                .replace(splatParam, '([^?]*?)');
            return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
        },

        check : function(v){
            var seg = location.hash.replace(/(^#|\/$)/g,"")
            var r;
            var l;
            for(var j=0;j< v.length;j++){
                l = this._routeToRegExp(v[j]).exec( seg );
                if(l != null){
                    r = [];
                    l = l.slice(1);
                    for(var i=0;i< l.length;i++)
                    {
                        if(l[i]===undefined) break;
                        r.push(l[i])
                    }
                }
            }
            return r;
        },

        history : function(){
            var self = this;
            window.addEventListener("hashchange", function(){
                self._onhashchange();
            });
            return this;
        },

        _onhashchange:function(){

            for(var i=this.routes.length ; i--;)
            {

                var argus = this.check(this.routes[i].route);

                if(argus != undefined){
                    this.routes[i].fn.apply(this.routes[i].fn , argus);
                    //return;
                }
            }

        },

        init : function(){
            this.step = window.history.length;
            this.parse().history()._onhashchange();
            return this;
        }
        ,

        add : function(route , fn , checkchange){
            this.routes.push({
                route : route.split(',') ,
                fn : fn
            })

            if(checkchange===true){
                this._onhashchange();
            }
        }
        ,
        parse : function(){
            return this;
        }
    }

    var routerInstance = new Router();
    routerInstance.init();

    // view-modal
    function vm(v){
        this._v = v;
        this.render = function(){

        }

        this.fetch = function(){

        }

    }

    vm.prototype = {
        _v : null
    }

    var T = function(){};

    T.define = function(){

    }

    T.router = {
        scan : function(el){
            $("[data-router]").each(function(){
                var id = $(this).attr("id") || (+new Date),
                    router = $(this).attr("data-router") || '',
                    link = $(this).attr(data-link);
            })
        },

        define : function(a,b,c){
            routerInstance.add(a,b,c);
        },

        init :function(){
            routerInstance._onhashchange();
        },

        get : function(){return routerInstance.routes;}
    }

    //cmd
    if ( typeof define === "function") {
        define(function(require, exports){
            return T;
        })
    }

    //让渡变量名
    var _T = window.T;
    T.noConflict = function( deep ) {
        if ( deep && window.T === T ) {
            window.T = _T;
        }
        return T;
    };

    //全局绑定
    if (noGlobal === undefined) {
        window.T = T
    }
    return T;
}));